<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * 供应商动销查询
 *
 */
class Controller_Stock extends Controller_Admin {

    public function before() {
        try {
            ACL::Required('single stock');
        } catch (HTTP_Exception_403 $e) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(true));
        }
        parent::before();
    }

    // 供应商动销查询
    public function action_index() {
        $this->title = __('供应商动销查询');
        $conditions = array();
        $supplier_id = 0;
        if (isset($_GET['sku']) && !empty($_GET['sku'])) {
            $conditions['sku'] = explode(',', $_GET['sku']);
        }
        if (isset($_GET['supplier_name']) && !empty($_GET['supplier_name'])) {
            $sql = "SELECT supplier_id FROM vmi_supplier_skus WHERE supplier_name='" . addslashes($_GET['supplier_name']) . "' AND isavailable=1 LIMIT 1";
            $supplier_id = DB::query(Database::SELECT,$sql)->execute('newerp')->get('supplier_id');
        }
        if (isset($_GET['supplier_id']) && !empty($_GET['supplier_id'])) {
            $supplier_id = intval($_GET['supplier_id']);
        }
        if($supplier_id) {
            $conditions['supplier_id'] = $supplier_id;
        }
        
        //针对60天销量
        $start_date = date('Y-m-d 00:00:00', time()-59*86400);
        $end_date = date('Y-m-d 23:59:59');
        if (isset($_GET['date_from']) && !empty($_GET['date_from'])) {
            $start_date = date('Y-m-d 00:00:00', strtotime($_GET['date_from']));
        }
        if (isset($_GET['date_to']) && !empty($_GET['date_to'])) {
            $end_date = date('Y-m-d 23:59:59', strtotime($_GET['date_to']));
        }
        // echo $start_date,' ',$end_date, ' --> ', abs(strtotime($end_date) - strtotime($start_date));
        $date_diff = round(abs(strtotime($end_date) - strtotime($start_date)) / 86400) . '天';
        $conditions['date'] = array($start_date, $end_date);
        if($_GET['act'] != 'export') {
            //分页
            $pagesize = 20;
            $total = Inventory::get_real_stocks(0, $conditions, 1);
            $pagination = Pagination::factory(array(
                'items_per_page' => $pagesize,
                'total_items' => $total,
                'uri' => $this->request->uri(),
            ));
            $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
            $start = ($page <= 1) ? 0 : (($page - 1) * $pagesize);
            $conditions['limit'] = $pagesize;
            $conditions['offset'] = $start;
        }
        $data = $this->getData($conditions);
        if($_GET['act'] == 'export') {
            $this->exportCsv($data, $date_diff);
            exit;
        }
        $warehouses = Kohana::$config->load('warehouse')->warehouses;

        $view = View::factory('inventory/select_inventory')->set('data', $data);
        $view->set("pagination", $pagination);
        $view->set('warehouses', $warehouses);
        $view->set('days', $date_diff);
        $this->response->body($view);
    }
    
    // 供应商动销查询导出csv
    protected function exportCsv($data, $days = ''){
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '2048M');
        $filename = '供应商动销报表_'.date('Ymd').'.csv';
        $warehouses = Kohana::$config->load('warehouse')->warehouses;
        $content = "供应商,SKU,中文名称,单位,仓库,当前库存量,{$days}销量\r\n";
        foreach($data['stocks'] as $v) {
            $product = $data['products'][$v['supplier_id']][$v['sku']];
            $row .= '"' . $product['supplier_name'] . '","' . $v['sku'] . '","' . $product['productname'] . '","' . $product['nuit'] . '","';
            $row .= $warehouses[$v['warehouseid']]['name'] . '","' . (int)$v['quantity'] . '","' . (int)$v['sales'] . '"';
            $row .= "\r\n";
        }
        $content .= $row;
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public');
        echo $content;exit;
    }

    // 供应商动销查询
    protected function getData($condition = array()) {
        $products = $sales = $stocks = $supplier_ids = $skus = array();
        $results = Inventory::get_real_stocks(0, $condition);
        if(!empty($results)) {
            foreach ($results as $row) {
                $supplier_ids[] = (int)$row['supplier_id'];
                $skus[] = $row['sku'];
                $key = $row['supplier_id'] . '_' . $row['sku'] . '_' . $row['warehouseid'];
                !isset($stocks[$key]) ? ($stocks[$key] = $row) : ($stocks[$key]['quantity'] += $row['quantity']);
            }
        }
        if(!empty($skus)) {
            $sql = "SELECT sku,supplier_id,supplier_name,productname,price,nuit FROM vmi_supplier_skus "
                . " WHERE supplier_id IN (" . implode(',', $supplier_ids) . ") AND sku IN ('" . implode("','", $skus) . "') AND isavailable=1";
            $rows = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
            if(!empty($rows)) {
                foreach($rows as $row) {
                    $products[$row['supplier_id']][$row['sku']] = $row;
                }
            }
            $results = Inventory::get_sales(10, array('supplier_id' => $supplier_ids, 'sku' => $skus, 'date' => $condition['date']));
            if(!empty($results)) {
                foreach($results as $row) {
                    $key = $row['supplier_id'] . '_' . $row['sku'] . '_' . $row['warehouseid'];
                    if(!isset($stocks[$key])) continue;
                    if(isset($stocks[$key]['sales'])) {
                        $stocks[$key]['sales'] += $row['quantity'];
                    } else {
                        $stocks[$key]['sales'] = $row['quantity'];
                    }
                }
            }
        }
        return array('stocks' => $stocks, 'products' => $products);
    }
}
